package com.dom;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;
import org.w3c.dom.NodeList;

import java.io.File;
import java.io.FileWriter;
import java.util.List;

public class Dom4JReader {
    //循环得到收藏信息.xml里的所有节点内容
    @Test
    public void testReaderAll()throws Exception{
        SAXReader reader=new SAXReader();
        //读取
        Document doc=reader.read(new File("src/main/resources/收藏信息.xml"));
        //获取根节点
        Element phoneInfoEl=doc.getRootElement();
        //得到一个List列表
        List<Element> brandEls=phoneInfoEl.elements("Brand");
        for (Element element:brandEls) {
            String brandName=element.attributeValue("name");
            List<Element> typeEls=element.elements("Type");
            for(Element typeEl:typeEls){
                String typeName=typeEl.attributeValue("name");
                System.out.println("手机品牌："+brandName+"，型号："+typeName);
            }
        }
    }


    //使用dom4j添加节点信息
    @Test
    public void testAddDom4J()throws  Exception{
        SAXReader reader=new SAXReader();
        //读取
        Document doc=reader.read(new File("src/main/resources/收藏信息.xml"));
        //获取根节点
        Element phoneInfoEl=doc.getRootElement();

        phoneInfoEl.addElement("Brand")
                .addAttribute("name","三星")
                .addElement("Type")
                .addAttribute("name","NodeY");
        FileWriter fw=new FileWriter("src/main/resources/收藏信息.xml");
        doc.write(fw);
        fw.close();
    }


}
